/**
 * 
 */
package com.pkdl.tables;

import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.TableColumn;

import com.pkdl.dao.BenhNhanChoKhamDAO;
import com.pkdl.dao.BenhNhanDAO;
import com.pkdl.dao.PhieuKhamDAO;
import com.pkdl.dto.BenhNhanChoKhamDTO;
import com.pkdl.dto.BenhNhanDTO;
import com.pkdl.dto.PhieuKhamDTO;
import com.pkdl.enums.TinhTrangKham;
import com.pkdl.forms.DlgCapNhatPhieuKham;
import com.pkdl.forms.DlgQuanLyBenhNhan;
import com.pkdl.helpers.CommonVars;

/**
 * @author Administrator
 * 
 */
public class TableBenhNhanHienThoi extends TableBase {
	private List<BenhNhanChoKhamDTO> lstItem;
	private BenhNhanChoKhamDAO bnckDAO;
	private PhieuKhamDAO pkDAO;
	private JTable table;

	public TableBenhNhanHienThoi(List<BenhNhanChoKhamDTO> _lstItem) {
		super();
		this.lstItem = _lstItem;
	}

	private void addElementIntoTable(List<BenhNhanChoKhamDTO> lstItem) {
		// arraylsit chua tat cac cac file tuong ung voi thu muc
		// co duong dan strTempPathLeft
		this.arrRow = new Vector<Object>();
		// ///////////////
		for (int i = 0; i < lstItem.size(); i++) {
			JLabel lb = new JLabel();
			String pathImages = "/com/pkdl/resources/vcard.png";

			ImageIcon imageIcon = new ImageIcon(
					DlgQuanLyBenhNhan.class.getResource(pathImages));

			if (imageIcon.getIconWidth() > this.PREFERRED_SIZE
					|| imageIcon.getIconHeight() > this.PREFERRED_SIZE) {
				imageIcon = new ImageIcon(imageIcon.getImage()
						.getScaledInstance(this.PREFERRED_SIZE,
								this.PREFERRED_SIZE, Image.SCALE_SMOOTH));
			}

			lb.setIcon(imageIcon);
			lb.setName(String.valueOf(lstItem.get(i).getMaBenhNhan()));
			lb.setHorizontalAlignment(SwingConstants.CENTER);

			BenhNhanDAO dao = new BenhNhanDAO();
			BenhNhanDTO dto = dao.selectById(lstItem.get(i).getMaBenhNhan());
			lstItem.get(i).setBenhNhan(dto);
			// them cac phan tu vao mang
			Vector<Object> a = new Vector<Object>();
			a.add(lb);// add icon
			a.add(lstItem.get(i).getBenhNhan().getHoTen());
			a.add(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(lstItem
					.get(i).getThoiDiemTiepNhan()));
			a.add(lstItem.get(i).getTinhTrang());

			JButton btn = new JButton();
			btn.setName("btnLPK_"
					+ String.valueOf(lstItem.get(i).getMaBenhNhan())
					+ "_"
					+ new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(
							lstItem.get(i).getThoiDiemTiepNhan()).toString());
			btn.setHorizontalAlignment(SwingConstants.CENTER);
			this.addMouseListenerToButton(btn);

			this.pkDAO = new PhieuKhamDAO();
			java.util.Date parsedDate = null;
			try {
				parsedDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
						.parse(btn.getName().split("_")[2]);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			PhieuKhamDTO phieukham = this.pkDAO
					.selectByThoiDiemTiepNhan(new Timestamp(parsedDate
							.getTime()));
			// Chua lap phieu kham cho benh nhan
			if (phieukham == null) {
				btn.setText("Lap phieu kham");
			} else {
				btn.setText("Cap nhat phieu kham");
				btn.setName(btn.getName() + "_" + phieukham.getMaPhieuKham());
			}

			a.add(btn);

			this.arrRow.add(a);
		}
	}

	private void addMouseListenerToButton(JButton btn) {
		MouseListener mouseListener = new MouseAdapter() {
			public void mousePressed(MouseEvent mouseEvent) {
				int modifiers = mouseEvent.getModifiers();

				if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
					if (TableBenhNhanHienThoi.this.table.getSelectedRow() == -1) {
						return;
					}

					if (TableBenhNhanHienThoi.this.table.getValueAt(
							TableBenhNhanHienThoi.this.table.getSelectedRow(),
							1) == null) {
						return;
					}

					// One click
					if (mouseEvent.getClickCount() == 1) {
						JButton btn = (JButton) mouseEvent.getSource();
						int mabenhnhan = Integer.parseInt(btn.getName().split(
								"_")[1]);

						// Lap phieu kham
						if (btn.getText().equals("Lap phieu kham")) {
							// Cap nhat tinh trang kham cua benh nhan
							TableBenhNhanHienThoi.this.bnckDAO = new BenhNhanChoKhamDAO();
							BenhNhanChoKhamDTO bnck = new BenhNhanChoKhamDTO();
							bnck.setMaBenhNhan(mabenhnhan);
							bnck.setTinhTrang(TinhTrangKham.DANGKHAM.toString());
							TableBenhNhanHienThoi.this.bnckDAO.update(bnck);

							// Lap phieu kham moi
							TableBenhNhanHienThoi.this.pkDAO = new PhieuKhamDAO();
							PhieuKhamDTO dto = new PhieuKhamDTO();
							dto.setMaBenhNhan(mabenhnhan);
							dto.setMaNguoiLapPhieu(CommonVars.g_oNguoiDung
									.getMaNguoiDung());
							dto.setNgayKham(new Date());
							try {
								dto.setThoiDiemTiepNhan(new Timestamp(
										new SimpleDateFormat(
												"dd/MM/yyyy HH:mm:ss").parse(
												btn.getName().split("_")[2])
												.getTime()));
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							// Insert phieu kham thanh cong
							if (TableBenhNhanHienThoi.this.pkDAO.insert(dto)) {
								btn.setText("Cap nhat phieu kham");
								JOptionPane.showMessageDialog(null,
										"Lap phieu kham thanh cong",
										"Announcement",
										JOptionPane.INFORMATION_MESSAGE);
							}

							// Cap nhat lai danh sach benh nhan cho kham
							TableBenhNhanHienThoi.this.bnckDAO = new BenhNhanChoKhamDAO();
							TableBenhNhanHienThoi.this.lstItem = TableBenhNhanHienThoi.this.bnckDAO
									.selectAll();
							TableBenhNhanHienThoi.this
									.addElementIntoTable(TableBenhNhanHienThoi.this.lstItem);
							// them dong, cot
							MyTableModel model = new MyTableModel(
									TableBenhNhanHienThoi.this.arrRow,
									TableBenhNhanHienThoi.this.arrCol, false);
							TableBenhNhanHienThoi.this.table.setModel(model);
						} else if (btn.getText().equals("Cap nhat phieu kham")) {
							// Hien thi form lap phieu kham
							DlgCapNhatPhieuKham dlg = new DlgCapNhatPhieuKham(
									null, true);
							dlg.MaBenhNhan = mabenhnhan;
							dlg.MaPhieuKham = Integer.parseInt(btn.getName()
									.split("_")[3]);
							try {
								dlg.ThoiDiemTiepNhan = new Timestamp(
										new SimpleDateFormat(
												"dd/MM/yyyy HH:mm:ss").parse(
												btn.getName().split("_")[2])
												.getTime());
							} catch (ParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							dlg.LoadCalendar();
							dlg.initTables();
							dlg.loadThongTinBenhNhan();
							dlg.loadDichVu();
							dlg.loadThuoc();
							dlg.show();
						}
					}
				}
			}
		};
		btn.addMouseListener(mouseListener);
	}

	public void editTable(JTable table1) {
		TableColumn column = null;
		// dieu chinh kich NguoiDung, do rong cac cot
		for (int i = 0; i < 5; i++) {
			column = table1.getColumnModel().getColumn(i);
			switch (i) {
			case 0:// icon
				column.setMaxWidth(20);
				break;
			case 1:// benh nhan
				column.setPreferredWidth((int) table1.getPreferredSize()
						.getWidth() / 4 - 20);
				break;
			case 2:// thoi diem tiep nhan
				column.setPreferredWidth((int) table1.getPreferredSize()
						.getWidth() / 4);
				break;
			case 3:// thoi diem tiep nhan
				column.setPreferredWidth((int) table1.getPreferredSize()
						.getWidth() / 4);
				break;
			case 4:// lap phieu kham
				column.setPreferredWidth((int) table1.getPreferredSize()
						.getWidth() / 4);
				break;
			}
			if (i == 0 || i == 4) {
				column.setCellRenderer(new MyImageCellRenderer());
			}
		}
		// tuy chinh font, ung voi cac item trong table (in dam)
		Font font = this.font;
		table1.setFont(font);
		table1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		table1.setSelectionBackground(Color.WHITE);
		table1.addMouseListener(new TableButtonMouseListener(table1));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.pkdl.tables.TableBase#loadDataIntoTableBook(javax.swing.JTable)
	 */
	public void loadDataIntoTable(JTable table) {
		this.table = table;
		// TODO Auto-generated method stub
		table.setRowHeight(18);
		this.arrCol = new Vector<String>();
		this.columnNames = new String[] { "", "BenhNhan", "ThoiDiemTiepNhan",
				"TinhTrang", "LapPhieuKham" };
		for (String strNameCol : this.columnNames) {
			this.arrCol.add(strNameCol);
		}

		this.addElementIntoTable(this.lstItem);
		// them dong, cot
		MyTableModel model = new MyTableModel(this.arrRow, this.arrCol, false);
		table.setModel(model);
		// thuc hien sort column theo tung loai (thu muc, file)
		// thu muc tang tu tren xuong duoi
		// sau do den file tang tu tren xuong duoi
		table.setAutoCreateColumnsFromModel(false);
		this.sortAllRowByFullName(model, 2, true);
		// /////////////
		this.editTable(table);
	}

}
